import sys
from typing import List, Optional

class PacketSniffer:
    """基于包头包尾的二进制数据流分割器（需在HexPacketSniffer前定义）"""
    def __init__(self):
        self.buffer = bytearray()
        self.header = 0xAA  # 包头
        self.footer = 0x2F   # 包尾

    def feed(self, data: bytes) -> None:
        self.buffer.extend(data)

    def extract(self) -> List[bytes]:
        packets = []
        while True:
            header_pos = self.buffer.find(self.header)
            if header_pos == -1: break
            
            remaining = self.buffer[header_pos:]
            footer_pos = remaining.find(self.footer)
            if footer_pos == -1: break
            
            packet_end = header_pos + footer_pos + 1
            packets.append(self.buffer[header_pos:packet_end])
            self.buffer = self.buffer[packet_end:]
        return packets

class HexPacketSniffer:
    """增强型十六进制字符串数据包截取器"""
    def __init__(self):
        self.raw_buffer = ""
        self.byte_sniffer = PacketSniffer()  # 现在可以正确引用
    
    def feed_str(self, hex_str: str) -> None:
        cleaned = hex_str.replace(" ", "").strip()
        if not cleaned: return
        
        # 处理奇数长度残留
        if self.raw_buffer:
            cleaned = self.raw_buffer + cleaned
            self.raw_buffer = ""
        
        if len(cleaned) % 2 != 0:
            self.raw_buffer = cleaned[-1]
            cleaned = cleaned[:-1]
        
        try:
            self.byte_sniffer.feed(bytes.fromhex(cleaned))
        except ValueError as e:
            print(f"HEX转换错误: {str(e)}")

    def extract_packets(self) -> List[bytes]:
        return self.byte_sniffer.extract()

# 使用示例
if __name__ == "__main__":
    hex_str = "AA 0B 20 81 03 00 00 02 0D 0A 00 00 00 72 2F AA 07 21 81 03 00 00 02 03 5B 2F AA 02 22 00 CE 2F"
    
    sniffer = HexPacketSniffer()
    sniffer.feed_str(hex_str)
    
    print("捕获数据包:")
    test_cases = []
    for pkt in sniffer.extract_packets():
        pkt_str = pkt.hex(' ').upper()
        print(pkt_str)
        test_cases.append(pkt_str)
    
    if sniffer.byte_sniffer.buffer:
        print(f"残留数据: {sniffer.byte_sniffer.buffer.hex()}")

    # 打印 test_cases 列表
    print("测试用例:")
    for case in test_cases:
        print(f'"{case}",')